package com.aofeng.hybridwork.android.task;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.StrictMode;

import com.aofeng.hybrid.activity.HybridActivity;
import com.aofeng.hybrid.android.NativeBaseMethod;
import com.aofeng.hybrid.service.RestService;
import com.aofeng.hybrid.service.SqlService;
import com.aofeng.hybridwork.application.HybridApplication;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 上传维修单异步任务
 * Created by LGY on 2016-08-25.
 */
public class UploadRepairTask extends AsyncTask<String, String, Boolean> {
    HybridActivity hybridActivity;

    public UploadRepairTask(HybridActivity hybridActivity) {
        this.hybridActivity = hybridActivity;
    }

    @Override
    /**
     * params:
     * 下载的url
     */
    protected Boolean doInBackground(String... params) {
        try {
            publishProgress(new String[]{ 0 + "", "保存维修单......"});
            JSONObject paper = new JSONObject(params[2]);
            SavePaperTask.savePaper(paper, params[0], params[1], hybridActivity, true);
            publishProgress(new String[]{ 5 + "", "上传开始......"});
            //JSONObject paper = FetchPaperTask.getPaper(params[0], params[1], hybridActivity);
            publishProgress(new String[]{ 10 + "", "上传图片开始......"});
            Map<String,String> map = new HashMap<>();
            getPicsAndAdjustCheckbox(paper.getJSONArray("f_defects"), map);
            int n = map.size();
            int i = 0;
            for(String key :map.keySet()) {
                if(!upload(key, map.get(key)))
                    return false;
                i++;
                publishProgress(new String[]{ (10 + ((70*i)/n)) + "", "上传图片" + i + "完成"});
            }
            //upload f_defects
            RestService rs = new RestService(hybridActivity);
            JSONObject joRequest = new JSONObject();
            joRequest.put("action", "post");
            joRequest.put("url", HybridApplication.LOGIC_SERVICE_URL + URLEncoder.encode("上传维修单", "UTF-8"));
            JSONObject data = new JSONObject();
            data.put("devices", paper.getJSONArray("f_defects"));
            JSONObject row = new JSONObject();
            row.put("data", data);
            joRequest.put("data", row);
            rs.execute(joRequest);
            // upload data
            rs = new RestService(hybridActivity);
            joRequest = new JSONObject();
            joRequest.put("action", "post");
            joRequest.put("url", HybridApplication.LOGIC_SERVICE_URL + URLEncoder.encode("通用更新", "UTF-8"));
            String sql = "update t_check_paper set f_repaired = '" +  paper.getString("f_repaired") + "', f_repaired_uploaded = '已传'";
            sql += ",f_repair_date = '" + paper.getString("f_repair_date") + "'";
            if(paper.getString("f_repair_approved").equals("打回"))
                sql += ", f_repair_approved='重修'";
            sql += " where f_check_item_id ='" + params[0] + "' and f_checker_id = '" + params[1] + "'";
            data = new JSONObject();
            data.put("sql", sql);
            row = new JSONObject();
            row.put("data", data);
            joRequest.put("data", row);
            rs.execute(joRequest);
            //修改客户端状态
            SqlService ss = new SqlService(hybridActivity);
            ss.run("update t_check_paper set f_repaired = '" +  paper.getString("f_repaired") + "', f_repaired_uploaded='已传' where f_check_item_id = '" + params[0] + "'");
            publishProgress(new String[]{ 100 + "", "上传成功。"});
            return true;
        } catch(Exception e) {
            return false;
        }
    }

    private boolean upload(String key, String fileName) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        try
        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext httpContext = new BasicHttpContext();
            String url = HybridApplication.BASE_URL + "/db/savefile" + "?FileName="
                    + URLEncoder.encode(key) + "&BlobId="
                    + URLEncoder.encode(key)
                    + "&EntityName=t_blob";
            HttpPost httpPost = new HttpPost(url);
            FileEntity entity = new FileEntity(new File(fileName), "binary/octet-stream");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost, httpContext);
            return response.getStatusLine().getStatusCode() == 200;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 维修照片
     * @param defects
     * @param map
     * @throws Exception
     */
    private void getPicsAndAdjustCheckbox(JSONArray defects, Map<String,String> map) throws Exception {
        // examine pic in each f_defects
        for(int i =0; i< defects.length(); i++) {
            JSONObject obj = defects.getJSONObject(i);
            String key = "f_ratified_path";
            if(!obj.isNull("f_ratified_path")) {
                String value = obj.getString("f_ratified_path");
                modifyPic(map, obj, key, value, true);
            }
            key = "f_defect_path";
            if(!obj.isNull("f_defect_path")) {
                String value = obj.getString("f_defect_path");
                modifyPic(map, obj, key, value, false);
            }
            Object v = obj.get("f_ratification");
            if(v.toString().equals("true") || v.toString().equals("false"))
                obj.put("f_ratification", obj.toString());
            obj.put("EntityType", "t_check_paper_defect");
        }
    }

    private void modifyPic(Map<String, String> map, JSONObject obj, String key, String value, boolean addFlag) throws JSONException {
        if (value.endsWith("nopic.png"))
            obj.put(key, null);
        else {
            if (value.startsWith("file://"))
                value = value.substring(7);
            int pos = value.lastIndexOf("/") + 1;
            int pos2 = value.indexOf("?");
            if (pos2 == -1)
                pos2 = value.length();
            String k = value.substring(pos, pos2);
            obj.put(key, k);
            if(addFlag)
                map.put(k, value.substring(0, pos2));
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        hybridActivity.createProgressDialog(ProgressDialog.STYLE_SPINNER);
    }

    @Override
    protected void onPostExecute(Boolean flag) {
        super.onPostExecute(flag);
        hybridActivity.closeProgress();
        if(flag)
            NativeBaseMethod.alert(hybridActivity.mWebView, "上传成功！");
        else
            NativeBaseMethod.alert(hybridActivity.mWebView, "上传失败！");
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        int progress = Integer.parseInt(values[0]);
        hybridActivity.setProgress(progress, values[1]);
    }
}
